package com.zkhz.base.security.authentication.handler;


import com.alibaba.fastjson.JSON;
import com.zkhz.base.common.dto.ResponseDTO;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录成功，以json格式返回给前端的处理器
 *
 * @author wuzeqin
 * @date 2020/5/29
 **/
@RequiredArgsConstructor
public class JwtAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private final AuthorizationServerTokenServices tokenServices;

    private final String clientId;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().println(JSON.toJSONString(ResponseDTO.ok(createToken(authentication))));
    }

    private OAuth2AccessToken createToken(Authentication authentication) {
        OAuth2Request oAuth2Request = new OAuth2Request(null, clientId, null, true, null, null, null, null, null);
        OAuth2Authentication auth2Authentication = new OAuth2Authentication(oAuth2Request, authentication);
        return tokenServices.createAccessToken(auth2Authentication);
    }
}
